﻿using System.IO;
using System.Net;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace garnisonen.Controllers
{
    public class HueController : Controller
    {
		const string HueUrl = "http://www.meethue.com/api/nupnp";

        public ActionResult Index()
        {
            return View();
        }

		[HttpGet]
		public JsonResult GetInfo()
		{
			var internalip = string.Empty;
			var error = string.Empty;
			var req = (HttpWebRequest)WebRequest.Create(HueUrl);
			req.ContentType = "application/json; charset=utf-8";
			var response = (HttpWebResponse) req.GetResponse();

		
			using (var sr = new StreamReader(response.GetResponseStream()))
			{
				JavaScriptSerializer js = new JavaScriptSerializer();
				var objects = js.Deserialize<dynamic>(sr.ReadToEnd());
				foreach (var o in objects[0])
				{
					if (o.Key == "internalipaddress") internalip = o.Value;
				}
			}
			if (string.IsNullOrEmpty(internalip))
			{
				error = "could not find ip";
			}
			return Json(new
				            {
					            IP=internalip,
								Error=error
				            },JsonRequestBehavior.AllowGet);
		}

    }
}
